﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RpcGenerator.AS3
{
    class AS3ProxyGenerator
    {
        public static void Generate(Type type, IMessageSerializer serializer, List<MessageDescription> allDescriptions)
        {
            MessageDescriptionGenerator mdgenerator = new MessageDescriptionGenerator();
            List<MessageDescription> requestDescriptions = allDescriptions.Where(description => description.IsRequest == true).ToList();

            string proxyName = RpcGeneratorHelper.GetProxyName(type);
            serializer.NewLine(string.Format("public class {0} extends RpcProxy", proxyName));
            serializer.BeginBlock();
            serializer.NewLine(string.Format("public function {0}(domain:RpcDomain,sessionid:int)", proxyName));            
                serializer.BeginBlock();
                    serializer.NewLine("super(domain, sessionid)");
                serializer.EndBlock();

                requestDescriptions.ForEach(description =>
                {
                    serializer.NewLine();
                    GenerateMethod(description, serializer);
                });
            serializer.EndBlock();
        }

        private static void GenerateMethod(MessageDescription description, IMessageSerializer serializer)
        {
            serializer.NewLine(string.Format("public function {0}(", description.Method.Method.Name));
            if (description.Fields.Count > 0)
            {
                MessageFieldDescription lastField = description.Fields[description.Fields.Count - 1];
                description.Fields.ForEach(fieldDescription =>
                {
                    if (lastField != fieldDescription)
                    {
                        serializer.Apppend(string.Format("{0}:{1},",fieldDescription.Name,RpcGeneratorHelper.GetParameterTypeName(fieldDescription.Type)));
                    }
                    else
                    {
                        serializer.Apppend(string.Format("{0}:{1}", fieldDescription.Name, RpcGeneratorHelper.GetParameterTypeName(fieldDescription.Type)));
                    }
                });
            }
            serializer.Apppend("):void");
            serializer.BeginBlock();
            serializer.NewLine(string.Format("var request:{0} = new {0}();", description.Name));
            description.Fields.ForEach(fieldDescription =>
            {
                serializer.NewLine(string.Format("request.{0} = {0};", fieldDescription.Name));
            });
            serializer.NewLine(string.Format("Invoke(request,{0});", description.NeedEncrypt ? "true" : "false"));
            serializer.EndBlock();
        }
    }
}
